package com.hnevc.androiduiclassone8;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QQloginActivity extends AppCompatActivity {
    EditText mEtNumber,mEtpassword;
    Button mBtnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qqlogin);
        initview();
        initEvent();
    }

    private void initEvent() {
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存所输入的用户名
                //1.获取数据
                String number=mEtNumber.getText().toString();
                String password=mEtpassword.getText().toString();
                //2.将数据保存到文件
                String data=number +":"+password;
                try {
                    FileOutputStream fos = openFileOutput("data.txt", MODE_PRIVATE);
                    fos.write(data.getBytes());
                    fos.close();
                    Toast.makeText(QQloginActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                //3.提示登录成功，数据保存成功


            }
        });
    }
    private Map<String, String> getUserInfo() {
        try {
            FileInputStream fi = openFileInput("data");
            byte[] bytes = new byte[fi.available()];
            fi.read(bytes);
            fi.close();
            String content = new String(bytes);
            String[] string = content.split(":");
            Map<String, String> map = new HashMap();
            map.put("number", string[0]);
            map.put("password", string[1]);
            return map;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private void initview() {
        mEtNumber=findViewById(R.id.et_number);
        mEtpassword=findViewById(R.id.et_password);
        mBtnLogin=findViewById(R.id.btn_login);
        Map<String,String> userInfo=getUserInfo();
        if (userInfo!=null){
            mEtNumber.setText(userInfo.get("number"));
            mEtpassword.setText(userInfo.get("password"));
        }
    }


}
